package com.lagou.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lagou.dao.UserMapper;
import com.lagou.domain.*;
import com.lagou.service.UserService;
import com.lagou.utils.Md5Helper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public PageInfo findAllUserByPage(UserVo userVo) {
        PageHelper.startPage(userVo.getCurrentPage(), userVo.getPageSize());
        List<User> allUserByPage = userMapper.findAllUserByPage(userVo);
        return new PageInfo<>(allUserByPage);
    }

    @Override
    public User login(User user) throws Exception {
        User user2 = userMapper.login(user);
        if (user2 != null && Md5Helper.verify(user.getPassword(), "lagou", user2.getPassword())) {
            return user2;
        }
        return null;
    }

    @Override
    public List<Role> findUserRelationRoleById(Integer userId) {
        return userMapper.findUserRelationRoleById(userId);
    }

    @Override
    public void userContextRole(UserVo userVo) {
        userMapper.deleteUserContextRole(userVo.getUserId());
        for (Integer roleId : userVo.getRoleIdList()) {
            User_Role_relation userRoleRelation = new User_Role_relation();
            userRoleRelation.setRoleId(roleId);
            userRoleRelation.setUserId(userVo.getUserId());
            Date date = new Date();
            userRoleRelation.setCreatedTime(date);
            userRoleRelation.setUpdatedTime(date);
            userRoleRelation.setCreatedBy("system");
            userRoleRelation.setUpdatedby("system");
            userMapper.userContextRole(userRoleRelation);
        }
    }

    @Override
    public ResponseResult getUserPermissions(Integer userId) {
        List<Role> roleList = userMapper.findUserRelationRoleById(userId);
        ArrayList<Integer> roleIds = new ArrayList<>();
        for (Role role : roleList) {
            roleIds.add(role.getId());
        }
        List<Menu> parentMenu = userMapper.findParentMenuByRoleId(roleIds);
        for (Menu menu : parentMenu) {
            menu.setSubMenuList(userMapper.findSubMenuByPid(menu.getId()));
        }
        List<Resource> resourceList = userMapper.findResourceByRoleId(roleIds);
        Map<String, Object> map = new HashMap<>();
        map.put("menuList", parentMenu);
        map.put("resourceList", resourceList);
        return new ResponseResult(true, 200, "success", map);
    }
}
